package com.example.springblog.controller;

import com.example.springblog.mapper.BlogMapper;
import com.example.springblog.model.BlogInfo;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.BlogService;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BlogService blogService;

    @RequestMapping("/login")
    public Result login(HttpServletRequest request, HttpServletResponse response, String userName, String password){
        if(!StringUtils.hasLength(userName)||!StringUtils.hasLength(password)){
            log.error("username:"+userName+",password:"+password);
            return null;
        }
        //判断账号密码是否正确
        UserInfo userInfo = userService.getUserInfo(userName);
        if(userInfo==null||userInfo.getId()<1){
            return Result.fail(-1,"用户存在");
        }
        if(!password.equals(userInfo.getPassword())){
            return Result.fail(-1,"密码错误");
        }
        //如果登录成功，返回Token
        Map<String ,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("name",userInfo.getUserName());
        String token = JWTUtils.genJwt(claims);

        System.out.println("生成的token:"+token);
        return Result.success(token);
    }

    //获取当前登录用户信息

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        //从header中获取token
        String jwtToken = request.getHeader("user_token");
        //从token中获取到id
        Integer userId = JWTUtils.getUserIdFromToken(jwtToken);

        //根据userid获取用户信息
        if(userId != null){
            return userService.getUserInfoById(userId);
        }
        return null;
    }

    //获取博客作者信息。
    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(Integer blogId){
        //判断id是否合法
        if(blogId<=0||blogId==null){
            return Result.fail(-1,"博客Id不正确");
        }
        //通过blogId,获取到作者信息
        BlogInfo blogInfo = blogService.getBlogDetail(blogId);
        UserInfo userInfo = userService.getUserInfoById(blogInfo.getUserId());
        return Result.success(userInfo);
    }
}
